import React, { useState, useEffect } from 'react'
import { Button, Table, Space, Modal, Input, Rate } from 'antd'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/lib/table'
import { getItemList, addItem, delItem, editItem } from '@/api/item'
import style from '@/pages/index.less'
import { useAddKey } from '@/hooks'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { message, Upload } from 'antd'
import type { UploadChangeParam } from 'antd/es/upload'
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'
import { getBase64, beforeUpload } from '@/utils/upload'

import AddItem from './components/AddItem'

interface DataType {
    key: React.Key;
    name: string;
    age: number;
    address: string;
    description: string;
}

type Props = {}

const desc = ['1', '2', '3'];
const { confirm } = Modal;

export default function List({ }: Props) {
    const [list, setList] = useState([])
    const [total, setTotal] = useState(0)
    // 添加弹框
    const [isModalVisible, setIsModalVisible] = useState(false)
    // 编辑弹框
    const [isEditModalVisible, setIsEditModalVisible] = useState(false)
    // 添加数据
    const [itemInfo, setItemInfo] = useState<{name?:string, icon?:string, star?:number, desc?:any, detail?:string}>({
        name: "",
        icon: "",
        star: 0,
        desc: "",
        detail: ""
    })
    // 编辑数据
    const [editItemInfo, setEditItemInfo] = useState({
        name: "",
        icon: "",
        star: 0,
        desc: "",
        detail: "",
        key: ""
    })
    const [pageInfo, setPageInfo] = useState({
        pagenum: 1,
        pagesize: 5
    })

    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            render: (_, __, index) => {
                return index + 1
            },
            width: 70,
            align: 'center'
        },
        { title: '装备名称', dataIndex: 'name', key: 'name', align: 'center' },
        {
            title: '图标',
            dataIndex: 'icon',
            key: 'icon',
            align: 'center',
            render: (icon) => {
                return <img style={{
                    width: 45
                }} src={icon} />
            },
        },
        { title: '星级', dataIndex: 'star', key: 'star', align: 'center' },
        {
            title: '操作',
            dataIndex: '',
            key: 'x',
            align: 'center',
            render: (row) => <Space>
                <Button
                    icon={<EditOutlined />}
                    onClick={() => {
                        setIsEditModalVisible(true)
                        setEditItemInfo(row)
                    }}
                    type="primary">编辑</Button>
                <Button icon={<DeleteOutlined />}
                    type="primary"
                    onClick={() => {
                        confirm({
                            title: '确定要删除嘛?',
                            icon: <ExclamationCircleOutlined />,
                            onOk() {
                                delItem(row._id)
                                init()
                            },
                            onCancel() {
                                message.info("取消删除")
                            }
                        })
                    }}
                    danger>删除</Button>
            </Space>,
        },
    ];

    // 上传
    const [loading, setLoading] = useState(false);

    // 新增上传
    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true)
            return
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj as RcFile, icon => {
                setLoading(false)
                setItemInfo({
                    ...itemInfo,
                    icon
                })
            });
        }
    };
    // 编辑上传
    const handleEdidChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true)
            return
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj as RcFile, icon => {
                setLoading(false)
                setEditItemInfo({
                    ...editItemInfo,
                    icon
                })
            });
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );


    const showModal = () => {
        setIsModalVisible(true);
    };

    // 添加弹框确定
    const handleOk = () => {
        setIsModalVisible(false)
        addItem(itemInfo)
        setItemInfo({})
        init()
    };

    // 编辑弹框确定
    const handleEditOk = () => {
        setIsEditModalVisible(false)
        editItem(editItemInfo["key"], editItemInfo)
        init()
    };

    // 添加弹框取消
    const handleCancel = () => {
        setIsModalVisible(false);
    };

    // 编辑弹框取消
    const handleEditCancel = () => {
        setIsEditModalVisible(false);
    };

    useEffect(() => {
        init()
    }, [pageInfo])

    // 初始化
    const init = () => {
        getItemList(pageInfo).then((res: any) => {
            const data = useAddKey(res.data)
            setTotal(res.total)
            setList(data)
        })
    }

    const changePageInfo = (page: any) => {
        setPageInfo({
            pagenum: page.current,
            pagesize: page.pageSize
        })
    }

    return (
        <div className={style.wrapperBox}>
            <Button type="primary" onClick={showModal}>+ 添加装备</Button>
            {/* 添加装备 */}
            <AddItem init={init}/>
            {/* <Modal title="添加装备" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
                <div className={[style.dis, style.mb20].join(" ")}>
                    <span className={style.right}>
                        物品名称
                    </span>
                    <div>
                        <Input value={itemInfo.name} onChange={(ev) => {
                            setItemInfo({
                                ...itemInfo,
                                name: ev.target.value
                            })
                        }} />
                    </div>
                </div>

                <div className={[style.dis, style.mb20].join(" ")}>
                    <span className={style.right}>
                        物品图标
                    </span>
                    <div>
                        <Upload
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            // 添加token字段
                            // headers={{
                            //     Authorization: "123"
                            // }}
                            action="/api/upload/item"
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            {itemInfo.icon ? <img src={itemInfo.icon} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </div>
                </div>

                <div className={[style.dis, style.mb20].join(" ")}>
                    <span className={style.right}>
                        星级
                    </span>
                    <div>
                        <span>
                            <Rate count={3} onChange={(star) => {
                                setItemInfo({
                                    ...itemInfo,
                                    star
                                })
                            }} value={itemInfo.star} />
                            <span className="ant-rate-text">
                                {itemInfo.star ? desc[itemInfo.star - 1] : '0'}
                            </span>
                        </span>
                    </div>
                </div>
                <div className={[style.dis, style.mb20].join(" ")}>
                    <span className={style.right}>
                        物品简介
                    </span>
                    <div>
                        <Input value={itemInfo.desc} onChange={(ev) => {
                            setItemInfo({
                                ...itemInfo,
                                desc: ev.target.value
                            })
                        }} />
                    </div>
                </div>
                <div className={style.dis}>
                    <span className={style.right}>
                        物品详情
                    </span>
                    <div>
                        <Input value={itemInfo.detail} onChange={(ev) => {
                            setItemInfo({
                                ...itemInfo,
                                detail: ev.target.value
                            })
                        }} />
                    </div>
                </div>
            </Modal> */}

            {/* 编辑装备 */}
            <Modal title="编辑装备" visible={isEditModalVisible} onOk={handleEditOk} onCancel={handleEditCancel}>
                <div className={[style.dis, style.mb20].join(" ")}>
                    <span className={style.right}>
                        物品名称
                    </span>
                    <div>
                        <Input value={editItemInfo.name}  onChange={(ev) => {
                            setEditItemInfo({
                                ...editItemInfo,
                                name: ev.target.value
                            })
                        }} />
                    </div>
                </div>

                <div className={[style.dis, style.mb20].join(" ")}>
                    <span className={style.right}>
                        物品图标
                    </span>
                    <div>
                        <Upload
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            // 添加token字段
                            // headers={{
                            //     Authorization: "123"
                            // }}
                            action="/api/upload/item"
                            beforeUpload={beforeUpload}
                            onChange={handleEdidChange}
                        >
                            {editItemInfo.icon ? <img src={editItemInfo.icon} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </div>
                </div>

                <div className={[style.dis, style.mb20].join(" ")}>
                    <span className={style.right}>
                        星级
                    </span>
                    <div>
                        <span>
                            <Rate count={3} onChange={(star) => {
                                setEditItemInfo({
                                    ...editItemInfo,
                                    star
                                })
                            }} value={editItemInfo.star} />
                            <span className="ant-rate-text">
                                {editItemInfo.star ? desc[editItemInfo.star - 1] : '0'}
                            </span>
                        </span>
                    </div>
                </div>
                <div className={[style.dis, style.mb20].join(" ")}>
                    <span className={style.right}>
                        物品简介
                    </span>
                    <div>
                        <Input value={editItemInfo.desc}  onChange={(ev) => {
                            setEditItemInfo({
                                ...editItemInfo,
                                desc: ev.target.value
                            })
                        }}/>
                    </div>
                </div>
                <div className={style.dis}>
                    <span className={style.right}>
                        物品详情
                    </span>
                    <div>
                        <Input value={editItemInfo.detail} onChange={(ev) => {
                            setEditItemInfo({
                                ...editItemInfo,
                                detail: ev.target.value
                            })
                        }}/>
                    </div>
                </div>
            </Modal>

            <div className={style.mt20}>
                <Table
                    columns={columns}
                    dataSource={list}
                    bordered
                    pagination={{
                        total,
                        pageSizeOptions: [5, 8, 10, 15],
                        defaultPageSize: 5,
                        pageSize: pageInfo.pagesize,
                        current: pageInfo.pagenum
                    }}
                    onChange={changePageInfo}
                    expandable={{
                        // 展开填充的内容
                        expandedRowRender: (record: any) => <p style={{ margin: 0, textAlign: 'center' }}>
                            {record.detail}
                        </p>,
                        // 不需要展开
                        // rowExpandable: record => record.name !== 'Not Expandable',
                    }}
                />
            </div>
        </div>
    )
}